package com.xbnmall.xbnmall.ssoclient.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpSession;
import javax.xml.crypto.Data;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * @author XBN
 * @date 2020/8/13 19:54
 * @email 78742541@qq.com
 */
@Controller
public class HelloController {
    @Value("${sso.server.url}")
    private String ssoServerUrl;
    /*
    * hello请求，无需登陆就可以访问
    * */
    @ResponseBody
    @GetMapping("/hello")
    public String hello(){
        return "hello";
    }

    /*
    * 登陆成功回调会带上token
    * */
    @GetMapping("/boss")
    public String employees(Model model, HttpSession session,
                            @RequestParam(value = "token",required = false) String token){

        if(!StringUtils.isEmpty(token))
        {
            //去验证服务器查询真正的用户信息
            RestTemplate restTemplate=new RestTemplate();
            ResponseEntity<String> forEntity = restTemplate.getForEntity("http://ssoserver.com:8080/userInfo?token=" + token, String.class);
            String user = forEntity.getBody();

            session.setAttribute("loginUser",user);
        }
        Object loginUser = session.getAttribute("loginUser");
        if(loginUser==null)
        {
            //没有登陆就跳转到登陆服务器去登陆

            return "redirect:"+ssoServerUrl+"?redirect_url=http://ssoClient2.com:8082/boss&u="+ UUID.randomUUID().toString().replaceAll("-","");
        }else {
            List<String> emps = new ArrayList<>();
            emps.add("张三");
            emps.add("李四");
            model.addAttribute("emps", emps);
            return "list";
        }
    }
}
